#include "dev_data.h"
#include "mqtt_parse.h"
#include <cstring>   // for memcpy
#include <algorithm> // for std::min

/**
 * @brief 将 DeviceHeartbeat 数据填充到 dev_data 结构体中
 *        仅填充 dev_data 中存在的字段，其余忽略
 * @param heartbeat 输入的心跳数据
 * @param data      输出的 dev_data 结构体（被填充）
 */
void fillDevDataFromHeartbeat(const DeviceHeartbeat &heartbeat, dev_data &data)
{
    // reg_heart: 心跳间隔（uint32_t → uint16_t，注意截断风险）
    data.reg_heart = static_cast<uint16_t>(heartbeat.HeartInterval);

    // reg_test_count: 测量次数统计
    data.reg_test_count = heartbeat.TestNum;

    // reg_alarm_count: 报警次数统计
    data.reg_alarm_count = heartbeat.AlarmNum;
}

/**
 * @brief 将 AlarmThresholdConfig 数据填充到 dev_data 结构体中
 *        仅填充 dev_data 中存在的对应字段，其余忽略
 * @param config 输入的报警阈值配置
 * @param data   输出的 dev_data 结构体（被填充）
 */
void fillDevDataFromAlarmThresholdConfig(const AlarmThresholdConfig &config, dev_data &data)
{
    // 填充报警模式
    data.reg_alarm_mode = config.alarm_mode;

    // 填充静态阈值
    data.reg_static_gamma_threshold = config.static_gamma_threshold;
    data.reg_static_beta_threshold = config.static_beta_threshold;
    data.reg_static_alpha_threshold = config.static_alpha_threshold;
    data.reg_static_gamma_severe = config.static_gamma_severe;
    data.reg_static_beta_severe = config.static_beta_severe;
    data.reg_static_alpha_severe = config.static_alpha_severe;

    // 填充动态系数
    data.reg_dynamic_gamma_coff = config.dynamic_gamma_coff;
    data.reg_dynamic_beta_coff = config.dynamic_beta_coff;
    data.reg_dynamic_alpha_coff = config.dynamic_alpha_coff;
    data.reg_dynamic_gamma_severe_coff = config.dynamic_gamma_severe_coff;
    data.reg_dynamic_beta_severe_coff = config.dynamic_beta_severe_coff;
    data.reg_dynamic_alpha_severe_coff = config.dynamic_alpha_severe_coff;

    // 其他字段（如 reg_heart, reg_test_count, reg_read_person_id 等）
    // 在 AlarmThresholdConfig 中无对应字段，不填充，保持原值
}
/**
 * @brief 将 rsp_data_info 数据填充到 dev_data 结构体中
 *        仅复制有对应字段的部分，其余忽略
 * @param rsp_info 输入的 RSP 数据
 * @param data     输出的设备数据结构
 */
void fillDevDataFromRspDataInfo(const rsp_data_info &rsp_info, dev_data &data)
{
    // 1. 单个字段：设备状态
    data.reg_status = rsp_info.reg_status;

    // 2. 数组字段
    const int copy_count = MAX_RSP_NUM;

    // 复制 RSP 状态
    std::memcpy(data.reg_rsp_status, rsp_info.reg_rsp_status, copy_count * sizeof(uint32_t));

    // time
    for (int i = 0; i < 6; i++)
    {
        data.reg_rtc_time[i] = rsp_info.Time[i];
    }
    // 复制 RSP 伽马值
    std::memcpy(data.reg_rsp_gama_valt, rsp_info.reg_rsp_gama_valt, copy_count * sizeof(float));

    // 复制 RSP 阿尔法值
    std::memcpy(data.reg_rsp_alpha_valt, rsp_info.reg_rsp_alpha_valt, copy_count * sizeof(float));

    // 复制 RSP 贝塔值（注意字段名拼写）
    std::memcpy(data.reg_rsp_bate_valt, rsp_info.reg_rsp_bate_valt, copy_count * sizeof(float));

    // PersonnelID
    int size = rsp_info.PersonnelID.size();
    size = std::min(size, (int)sizeof(data.reg_read_person_id));
    std::memcpy(data.reg_read_person_id, rsp_info.PersonnelID.c_str(), size * sizeof(char));

    // RSP数量查询
    data.reg_rsp_num = rsp_info.RSPCount;

    // RSP使用位
    data.reg_rsp_use_bit = rsp_info.RSPUseBit;
}

/**
 * @brief 打印 dev_data 结构体内容到日志
 * @param data 要打印的结构体
 * @param label 标签，用于区分不同调用场景（可选）
 */
void zlogDevData(zlog_category_t *zlog_mqtt, const dev_data &data, const char *label)
{
    static char buffer[4096];
    int offset = 0;
    zlog_info(zlog_mqtt, "------------------------------rsp data start--------------------------------------------------");
    // 基本字段
    offset += snprintf(buffer + offset, sizeof(buffer) - offset,
                       "[%s] \nheart=%u, \ntest_count=%u, \nalarm_count=%u, "
                       "\nalarm_mode=%u, \nstatus=%u, \nalarm_pub=%u, \npower_off=%u   \rsp_num=%u, \rsp_use_bit=%u",
                       label,
                       data.reg_heart,
                       data.reg_test_count,
                       data.reg_alarm_count,
                       data.reg_alarm_mode,
                       data.reg_status,
                       data.reg_alarm_pub,
                       data.reg_power_off,
                       data.reg_rsp_num,
                       data.reg_rsp_use_bit);

    // reg_read_person_id[10]
    offset += snprintf(buffer + offset, sizeof(buffer) - offset, "\nperson_id=[%s]", (char *)data.reg_read_person_id);

    // reg_rtc_time[6]: 年月日时分秒
    offset += snprintf(buffer + offset, sizeof(buffer) - offset,
                       ", \nrtc=%04u-%02u-%02u %02u:%02u:%02u | ",
                       data.reg_rtc_time[0], data.reg_rtc_time[1], data.reg_rtc_time[2],
                       data.reg_rtc_time[3], data.reg_rtc_time[4], data.reg_rtc_time[5]);

    // 静态阈值
    offset += snprintf(buffer + offset, sizeof(buffer) - offset,
                       "\nstatic_th(g=%.4f,b=%.4f,a=%.4f), "
                       "\nstatic_sev(g=%.4f,b=%.4f,a=%.4f) \n ",
                       data.reg_static_gamma_threshold,
                       data.reg_static_beta_threshold,
                       data.reg_static_alpha_threshold,
                       data.reg_static_gamma_severe,
                       data.reg_static_beta_severe,
                       data.reg_static_alpha_severe);

    // 动态系数
    offset += snprintf(buffer + offset, sizeof(buffer) - offset,
                       "\ndyn_coff(g=%.4f,b=%.4f,a=%.4f), "
                       "\ndyn_sev_coff(g=%.4f,b=%.4f,a=%.4f) \n ",
                       data.reg_dynamic_gamma_coff,
                       data.reg_dynamic_beta_coff,
                       data.reg_dynamic_alpha_coff,
                       data.reg_dynamic_gamma_severe_coff,
                       data.reg_dynamic_beta_severe_coff,
                       data.reg_dynamic_alpha_severe_coff);

    // RSP 状态（前5个）
    int rsp_log_count = data.reg_rsp_num;
    offset += snprintf(buffer + offset, sizeof(buffer) - offset,
                       "\nrsp_status=[");
    for (int i = 0; i < rsp_log_count; ++i)
    {
        offset += snprintf(buffer + offset, sizeof(buffer) - offset,
                           "%08X%s", data.reg_rsp_status[i], (i < rsp_log_count - 1) ? "," : "]\n");
    }

    // RSP 值（alpha, bate, gama）
    for (int i = 0; i < rsp_log_count; ++i)
    {

        offset += snprintf(buffer + offset, sizeof(buffer) - offset,
                           ", \n rsp%02u[(alpha=%.4f,beta=%.4f,gamma=%.4f)]",
                           i,
                           data.reg_rsp_alpha_valt[i],
                           data.reg_rsp_bate_valt[i],
                           data.reg_rsp_gama_valt[i]);
    }

    // 防止溢出
    if (offset >= (int)sizeof(buffer))
    {
        offset = sizeof(buffer) - 1;
    }
    buffer[offset++] = '\n';
    buffer[offset++] = '\0';
    // 输出日志
    zlog_info(zlog_mqtt, "%s", buffer);
    zlog_info(zlog_mqtt, "------------------------------rsp data end---------------------------------%u-----------------", strlen(buffer));
}